﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ktcar.Cs.Core.Logging;

namespace KtcAr.Services.Monitors
{
    public class SocketConnectMonitor : PingMonitor
    {
        protected int port;

        #region Constructor

        public SocketConnectMonitor(string aHost, int aPort) : base (aHost)
        {
            this.port = aPort;
        }

        #endregion

        /// <summary>
        /// Validate if the host is reacheable in the port specified by parameter
        /// </summary>
        /// <param name="port">port that will be used to validate if the host is reacheable</param>
        /// <returns>True if it is reacheable, False if not</returns>
        public bool IsReacheable()
        {
            try
            {
                var socket = new System.Net.Sockets.Socket(
                    System.Net.Sockets.AddressFamily.InterNetwork,
                    System.Net.Sockets.SocketType.Raw,
                    System.Net.Sockets.ProtocolType.Icmp);

                socket.Connect(this.host, this.port);

                return socket.Connected;
            }
            catch (Exception ex)
            {
                LogInterface.Log(this, ex, LogKind.Error);
                return false;
            }
        }
        public override MonitorResult CheckIt()
        {
            var result = base.CheckIt();
            result.ServiceResult = this.IsReacheable();
            return result;
        }
    }
}
